package com.whately.core.base.fileupload.fdfs;

import com.whately.core.base.exception.ServiceException;
import com.whately.core.base.fileupload.constants.DfsConst;
import com.whately.core.base.fileupload.vo.UploadFileRespVO;
import com.whately.core.base.model.ApiResponse;
import com.whately.core.base.utils.ObjectMapperUtil;
import com.whately.core.base.utils.http.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class FdfsFileUploadStaticHelper {

    //http://0.0.0.0:xxx/fs
    //http://0.0.0.0:xxx/fs/api/?method=whately.support.fs.fastdfs.upload
    private static String serverUrl;
    private static String accessKey;

    @Value("${support.fs.store.server:http://0.0.0.0:8883/fs}")
    public void setServerUrl(String serverUrl){
        FdfsFileUploadStaticHelper.serverUrl = serverUrl;
    }

    @Value("${support.fs.store.accessKey:}")
    public void setAccessKey(String accessKey){
        FdfsFileUploadStaticHelper.accessKey = accessKey;
    }


    /**
     * 上传
     * 文件上传 必须指定enctype="multipart/form-data"
     */
    public static UploadFileRespVO fdfsUpload(MultipartFile file){

        String url = serverUrl+"/api";
        Map<String,String> otherParams = new HashMap<>();
        otherParams.put("method", DfsConst.fdfs_upload_api_method_name);
        otherParams.put("accessKey",accessKey);
        String result = HttpClientUtil.postUploadFile(url,file,null,otherParams);
        if(StringUtils.isEmpty(result)){
            throw new ServiceException(400,"上传文件失败");
        }

        try{
            ApiResponse<UploadFileRespVO> apiResponse = ObjectMapperUtil.getObjectMapper().readValue(result,ObjectMapperUtil.getJavaType(ApiResponse.class,UploadFileRespVO.class) );
            return apiResponse.getData();
        }catch (Exception e){
            throw new ServiceException(400,"上传文件失败");
        }
    }

}
